<?php

namespace ASW\Utility\Logging;


use Throwable;

class Logger
{
    /**
     * @var ILogProvider[]
     */
    private static array $providers = [];

    /**
     * @var Logger[]
     */
    private static array $loggers = [];

    private function __construct(public string $category = '')
    {
    }

    public static function get(string $category = ''): static
    {
        $categoryKey = empty($category) ? "_" : $category;
        if (!array_key_exists($categoryKey, static::$loggers)) {
            static::$loggers[$categoryKey] = new static($category);
        }
        return static::$loggers[$categoryKey];
    }

    public static function addProvider(ILogProvider $provider): void
    {
        self::$providers[] = $provider;
    }

    public function debug(string $content, Throwable $throwable = null): void
    {
        $this->log(LogLevel::DEBUG, $content, $throwable);
    }

    public function log(LogLevel $logLevel, string $message, Throwable $throwable = null): void
    {
        foreach (static::$providers as $provider) {
            $provider->log($logLevel, $this->category, $message, $throwable);
        }
    }

    public function info(string $content, Throwable $throwable = null): void
    {
        $this->log(LogLevel::INFO, $content, $throwable);
    }

    public function warn(string $content, Throwable $throwable = null): void
    {
        $this->log(LogLevel::WARN, $content, $throwable);
    }

    public function error(string $content, Throwable $throwable = null): void
    {
        $this->log(LogLevel::ERROR, $content, $throwable);
    }
}